package com.xianggu.mybatis.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SqlParserTool {
    private static Pattern pattern = Pattern.compile("#\\{([^}]*)\\}");
    public static void main(String[] args) {
        String sql = "select from elssubaccountinfo where realname = #{realname} and els_account = #{elsAccount}";
        List <String> placeholders = new ArrayList<>();
        String newSql = SqlParserTool.parseSql(sql, placeholders);
        System.out.println("解析后的SQL: " + newSql); System.out.println("占位符内容: " + placeholders);

        String input = "user_id";
        System.out.println(convertToCamelCase(input));
    }

    /**
     * 将字符串的下换线转换成驼峰命名
     * @param input
     * @return
     */
    public static String convertToCamelCase(String input) {
        String[] parts = input.split("_");
        StringBuilder camelCase = new StringBuilder(parts[0]);
        for (int i = 1; i < parts.length; i++) {
            String part = parts[i];
            camelCase.append(part.substring(0, 1).toUpperCase()).append(part.substring(1));
        }
        return camelCase.toString();
    }

    /**
     * 将sql中的 #{xxx} 替换为 ?
     * @param sql
     * @param placeholders
     * @return
     */
    public static String parseSql(String sql, List<String> placeholders) {
        Matcher matcher = pattern.matcher(sql);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            placeholders.add(matcher.group(1));
            matcher.appendReplacement(sb, "?");
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
}